<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车牌" prop="plateNo">
        <el-input v-model="queryParams.plateNo" placeholder="请输入车牌" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label-width="auto" label="车号 / 自编号" prop="numbered">
        <el-input v-model="queryParams.numbered" placeholder="请输入车号/自编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-tree-select v-model="queryParams.deptId" @keyup.enter="handleQuery" :data="deptOptions"
          :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门" check-strictly
          clearable filterable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['basic:vehicle:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['basic:vehicle:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['basic:vehicle:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['basic:route:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['basic:vehicle:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border stripe v-loading="loading" :data="vehicleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" fixed="left" />
      <el-table-column label="车牌" align="left" prop="plateNo">
        <template #default="scope">
          <el-tag>{{ scope.row.plateNo }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="车号 / 自编号" align="left" prop="numbered" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <dict-tag :options="sys_data_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="部门" align="left" prop="deptName" :show-overflow-tooltip="true" />
      <el-table-column label="联系人" width="150" align="center" prop="contacts" />
      <el-table-column label="联系人电话" width="120" align="center" prop="contactPhone" />
      <el-table-column label="车牌颜色" align="center" prop="color" width="80">
        <template #default="scope">
          <dict-tag :options="basic_vehicle_color" :value="scope.row.color" />
        </template>
      </el-table-column>
      <el-table-column label="车辆类型" align="left" prop="type" width="150">
        <template #default="scope">
          <dict-tag :options="basic_vehicle_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="联网联控状态" align="center" prop="netState" width="110">
        <template #default="scope">
          <dict-tag :options="sys_enable" :value="scope.row.netState" />
        </template>
      </el-table-column>
      <el-table-column label="营运线路" width="150" align="left" prop="operationRoute" />
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['basic:vehicle:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['basic:vehicle:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改车辆对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <EditVehicle ref="vehicleRefEdit" :form="form" @opEnd="listenSubmitForm" />
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" action="#" :http-request="httpRequest"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag :data="upload.form">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <el-form :model="upload.form" ref="uploadForm" label-width="100px">
              <el-form-item label="部门" :rules="{ required: true, message: '部门不能为空', trigger: 'change' }" prop="deptId">
                <el-tree-select v-model="upload.form.deptId" :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门"
                  check-strictly filterable />
              </el-form-item>
            </el-form>
            <br />
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Vehicle">
import EditVehicle from '@/views/basic/vehicle/components/edit'
import { getToken } from "@/utils/auth"
import { listVehicle, getVehicle, delVehicle, addVehicle, updateVehicle } from "@/api/basic/vehicle";
import { deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const {
  basic_vehicle_color,
  basic_vehicle_type,
  sys_enable,
  sys_data_status
} = proxy.useDict(
  'basic_vehicle_color',
  'basic_vehicle_type',
  'sys_enable',
  'sys_data_status'
);

const vehicleList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref([])

/** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  form: {
    deptId: undefined,
  },
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: "basic/vehicle/import/data"
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    plateNo: undefined,
    numbered: undefined,
    deptId: undefined,
  }
});

const { queryParams, form } = toRefs(data);

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

/** 查询车辆列表 */
function getList() {
  loading.value = true;
  listVehicle(queryParams.value).then(response => {
    vehicleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    plateNo: null,
    numbered: null,
    status: '0',
    deptId: deptOptions.value[0].id,
    contacts: null,
    contactPhone: null,
    vin: null,
    color: 2,
    type: 10,
    netState: 1,
    operationRoute: null,
    engineNumber: null,
    operationNumber: null,
    address: null,
    monitorType: 0,
    platformType: 0,
    transportType: null,
    fleetName: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("vehicleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加车辆";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getVehicle(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改车辆";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["vehicleRefEdit"].submitForm();
  return false;
}

function listenSubmitForm(obj) {
  if (obj.status == 'success') {
    open.value = false;
    getList();
  } else {
    buttonLoading.value = false;
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除车辆编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delVehicle(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = '车辆导入';
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("basic/vehicle/import/template", {
  }, `vehicle_template_${new Date().getTime()}.xlsx`);
};

/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};


/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadForm"].validate((valid) => {
    if (valid) {
      proxy.$refs["uploadRef"].submit();
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};

function httpRequest(data) {
  // 封装FormData对象
  data.data[data.filename] = data.file
  upload.open = false;
  upload.isUploading = false;
  proxy.importFile(upload.url, data.data).then(res => {
    console.log('import result', res)
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + res.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  }).catch(err => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + err + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('basic/vehicle/export', {
    ...queryParams.value
  }, `vehicle_${new Date().getTime()}.xlsx`)
}

getDeptTree();

getList();
</script>
